package com.newlink.building.activity

import android.content.Context
import android.content.Intent
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.newlink.building.R
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.constant.Base_Constant
import com.newlink.building.common_base.model.bean.PolicyAgreementData
import com.newlink.building.common_base.utils.Base_Preference
import com.newlink.building.common_base.widget.CustomMessageDialog
import com.newlink.building.databinding.ActivityPolicyAndTermsBinding
import com.newlink.building.login.widget.Module_Login_PolicyClickableSpan
import com.newlink.building.login.widget.Module_Login_UserClickableSpan
import com.newlink.building.mvp.contract.NL_LicenseContract
import com.newlink.building.mvp.presenter.NL_LicensePresenter
import com.newlink.building.splash.NL_SplashActivityNL
import com.newlink.building.utils.Module_Phone_CountdownWorker
import kotlin.system.exitProcess

/**
 * Created by xiaodong on 2025/1/9.
 */
class NL_LicensePopupActivityNL :
    NL_BaseMvpActivity<NL_LicenseContract.View, NL_LicenseContract.Presenter>(),
    NL_LicenseContract.View {

    private lateinit var mBinding: ActivityPolicyAndTermsBinding
    private var isAppFirstLoad: Boolean by Base_Preference(Base_Constant.APP_FIRST_LOAD, true)
    private var spannableString: SpannableStringBuilder? = null
    private var countdownWorker: Module_Phone_CountdownWorker? = null
    private var countDownTime: Long = 5000L
    private val policyClickableSpan: Module_Login_PolicyClickableSpan by lazy {
        Module_Login_PolicyClickableSpan(this)
    }
    private val policyClickableSpan2: Module_Login_PolicyClickableSpan by lazy {
        Module_Login_PolicyClickableSpan(this)
    }
    private val userClickableSpan: Module_Login_UserClickableSpan by lazy {
        Module_Login_UserClickableSpan(this)
    }

    override fun attachLayoutRes(): View? {
        mBinding = ActivityPolicyAndTermsBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initData() {
        mPresenter?.getAgreement()
        initCountdownWorker()
        mBinding.btnAgree.setOnClickListener {
            isAppFirstLoad = false
            startActivity(Intent(this, NL_SplashActivityNL::class.java))
            finish()
        }
        mBinding.btnDisagree.setOnClickListener {

            val dialog =
                CustomMessageDialog(this).setTitle(getString(R.string.user_register_license_content))
                    .setMessage(
                        resources.getString(
                            R.string.content_dialog_policy_and_terms,
                            resources.getString(R.string.app_name_smart)
                        )
                    )
                    .setPositiveButton(
                        resources.getString(R.string.agree_dialog_custom)
                    ) { dialog ->
                        dialog.dismiss()
                    }
                    .setNegativeButton(
                        resources.getString(R.string.disagree_dialog_custom)
                    ) { dialog ->
                        android.os.Process.killProcess(android.os.Process.myPid())
                        exitProcess(0)
                    }
            dialog.setCancelable(false)
            dialog.show()
        }
    }

    override fun createPresenter() = NL_LicensePresenter()

    override fun initView() {
        lifecycle.addObserver(policyClickableSpan)
        lifecycle.addObserver(userClickableSpan)
        setSpannableStringView(
            this,
            mBinding.tvContent,
            getString(R.string.user_register_license_user),
            getString(R.string.user_register_license_privacy),
            getString(R.string.content_policy_and_item)
        )
    }

    private fun setSpannableStringView(
        context: Context,
        tv: TextView,
        userContent: String,
        policyContent: String,
        allContent: String,
    ) {
        var spanContent = allContent
        spanContent = spanContent.replace("####", userContent)
        spanContent = spanContent.replace("****", policyContent)

        val index1 = spanContent.indexOf(userContent)
        val index2 = spanContent.indexOf(policyContent)
        val index3 = spanContent.lastIndexOf(policyContent)

        spannableString = SpannableStringBuilder(spanContent)

        spannableString?.apply {
            setSpan(
                userClickableSpan,
                index1,
                index1 + userContent.length,
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE
            )
            setSpan(
                ForegroundColorSpan(ContextCompat.getColor(context, R.color.tablayout_indicator)),
                index1,
                index1 + userContent.length,
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE
            )
        }
        spannableString?.apply {
            setSpan(
                policyClickableSpan,
                index2,
                index2 + policyContent.length,
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE
            )
            setSpan(
                ForegroundColorSpan(ContextCompat.getColor(context, R.color.tablayout_indicator)),
                index2,
                index2 + policyContent.length,
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE
            )
        }

        spannableString?.apply {
            setSpan(
                policyClickableSpan2,
                index3,
                index3 + policyContent.length,
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE
            )
            setSpan(
                ForegroundColorSpan(ContextCompat.getColor(context, R.color.tablayout_indicator)),
                index3,
                index3 + policyContent.length,
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE
            )
        }

        tv.text = spannableString
        tv.movementMethod = LinkMovementMethod.getInstance()
    }

    private fun initCountdownWorker() {
        if (countdownWorker == null) {
            countdownWorker = Module_Phone_CountdownWorker(countDownTime)
            countdownWorker?.setListener(countdownWorkerListener)
        }
        countdownWorker?.start()
    }

    private val countdownWorkerListener = object : Module_Phone_CountdownWorker.CountdownListener {
        override fun onTick(millisUntilFinished: Long) {
            // 从30s开始显示
            val seconds = (millisUntilFinished + 900) / 1000
            mBinding.btnAgree.text = getString(R.string.agree_dialog_custom) + "(" + seconds + ")"
            mBinding.btnAgree.isEnabled = false
        }

        override fun onFinish() {
            mBinding.btnAgree.text = getString(R.string.agree_dialog_custom)
            mBinding.btnAgree.isEnabled = true
        }
    }

    override fun onGetAgreementSuccess(data: PolicyAgreementData) {
        policyClickableSpan.setUrl(data.policyPath)
        policyClickableSpan2.setUrl(data.policyPath)
        userClickableSpan.setUrl(data.agreementPath)
    }
}
